package org.jash.shop2111.detail

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import org.jash.shop2111.entry.CartItem
import org.jash.shop2111.entry.Goods
import org.jash.shop2111.mvvm.BaseViewModel
import org.jash.shop2111.net.user
import org.jash.shop2111.utils.bus
import org.jash.shop2111.utils.dao.CartItemDao
import javax.inject.Inject

@HiltViewModel
class DetailViewModel @Inject constructor(val cartItemDao: CartItemDao):BaseViewModel() {
    val goodsLiveData by lazy { MutableLiveData<Goods>() }
    val addCartLiveData by lazy { MutableLiveData<String>() }
    fun loadGoods(id:Int) {
        viewModelScope.launch {
            try {
                val res = service.getGoodsDetail(id)
                if (res.code == 200) {
                    goodsLiveData.postValue(res.data)
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
    fun addCart(goods: Goods) {
        viewModelScope.launch {
            try {
                val res = service.addCart(mapOf("goods_id" to goods.id, "count" to 1))
                if (res.code == 200) {
                    addCartLiveData.postValue(res.message)
                    user?.let {
                        val item = cartItemDao.findByGoodsId(it.id, goods.id)
                        if (item == null) {
                            bus.postValue("cartNumberChange" to 1)
                        }
                    }
                } else {
                    errorLiveData.postValue(RuntimeException(res.message))
                }
            } catch (e:Exception) {
                errorLiveData.postValue(e)
            }
        }
    }
}